﻿using System.Configuration;
using LY.Entity;
using LY.Entity.Entities;
using LY.Entity.Jsons;
using LY.Entity.PageSearch;
using LY.Entity.SearchEntity;
using LY.Interface;
using LY.Common.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Mail;
using System.Net;
using LY.Extension;


namespace QJ.CMS.Areas.Admin.Controllers
{

    public class MemberController : MyControllerBase
    {

        private static string _merchantNo = ConfigurationManager.AppSettings["merchantNo"];
        private static string _backAddress = ConfigurationManager.AppSettings["BackAddress"];
        private static string _apiAddress = ConfigurationManager.AppSettings["ApiAddress"];
        // GET: /Member/
        private IBlackMemberService _bservice;
        private IMemberService _mservice;
        private IDeptService _dept;
        private IUserService _uservice;
        private IInformationService _Iservice;
        private IMemberLogService _memberLogService;
        private static IBlackMemberService _blackservice;
        S_User loguser = null;
        public MemberController(IMemberService mService,IDeptService dept, IUserService uservice,IInformationService infoservice,IMemberLogService iMemberLogService,IBlackMemberService blackservice)
        {
            _mservice = mService;
            _dept = dept;
            _uservice = uservice;
            _Iservice = infoservice;
            _memberLogService = iMemberLogService;
            _blackservice = blackservice;
            if (System.Web.HttpContext.Current.Session["LoginUseInfo"] != null)
            {
                loguser = (S_User)System.Web.HttpContext.Current.Session["LoginUseInfo"];
            }
            else
            {
                loguser = new S_User();
            }

        }
        
        public ActionResult SysLetterlist() 
        {
            return View();
        }
        
        [HttpPost]
        public JsonResult SysLetterlist(InformationSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            PagedList<U_Information_EX> list = _mservice.QuerySystemInformation(search,view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<U_Information_EX>(list, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        //****会员信息*******//
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult AssignDept()
        {
            return View();
        }

        //部门待分配
        public ActionResult DeptAssign()
        {
            return View();
        }
        public ActionResult SysLetter() 
        {
            return View();
        }
        /// <summary>
        /// 部门弹出窗
        /// </summary>
        /// <returns></returns>
        public ActionResult DeptAssignPop()
        {
            List<S_Dept> List = _dept.GetDeptList();
            return View(List);
        }

        //部门会员
        public ActionResult DeptMember()
        {
            return View();
        }

        //客服待分配
        public ActionResult MemberAssign()
        {
            return View();
        }
        public ActionResult MessageAuditlist()
        {
            return View();
        }
        /// <summary>
        /// 分配到客服
        /// </summary>
        /// <returns></returns>
        public ActionResult MemberAssignPop()
        {
            S_User user = (S_User)System.Web.HttpContext.Current.Session["LoginUseInfo"];
            int deptid = user.DeptID;
            List<S_User> List = _uservice.GetUserList(deptid);
            return View(List);
        }

        //我的会员
        public ActionResult MyMember()
        {
            return View();
        }

        //***密码信息**//
        public ActionResult PwdEdit(int? id)
        {

            Member_EX m = null;
            if (id.HasValue)
            {
                m = _mservice.GetMember(id.Value);
            }
            else
            {
                m = new Member_EX();
            }
            return View(m);

        }

        public ActionResult Message()
        {
            return View();
        }
        public ActionResult SendMail(string name)
        {

            ViewBag.Name = name;
            return View();
        }
        //会员列表分页查询
        [HttpPost]
        public JsonResult MembertList(MemberSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            S_User user =(S_User)System.Web.HttpContext.Current.Session["LoginUseInfo"];
            int userid = user.ID;
            PagedList<Member_EX> mList = _mservice.QueryMemberList(search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<Member_EX>(mList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        /// <summary>
        /// 我的会员
        /// </summary>
        /// <param name="search"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UserMembertList(MemberSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            S_User user = (S_User)System.Web.HttpContext.Current.Session["LoginUseInfo"];
            int userid = user.ID;
            PagedList<Member_EX> mList = _mservice.QueryMemberListByUser(search, user.ID, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<Member_EX>(mList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        [HttpPost]
        public JsonResult DeptMembertList(MemberSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            S_User user = (S_User)System.Web.HttpContext.Current.Session["LoginUseInfo"];
            int deptid = user.DeptID;
            PagedList<Member_EX> mList = _mservice.QueryMemberListByDept(search, deptid, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<Member_EX>(mList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        [HttpPost]
        public JsonResult MemberAssign(MemberSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            S_User user = (S_User)System.Web.HttpContext.Current.Session["LoginUseInfo"];
            int deptid = user.DeptID;
            //S_User user =(S_User)System.Web.HttpContext.Current.Session["LoginUseInfo"];
            //int userid = user.ID;
            //PagedList<U_Member> mList = _mservice.QueryMemberListByUser(search,user.ID, view);
            PagedList<U_Member> mList = _mservice.QueryAssignMemberList(search, deptid, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<U_Member>(mList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        [HttpPost]
        public JsonResult DeptAssign(MemberSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            //S_User user =(S_User)System.Web.HttpContext.Current.Session["LoginUseInfo"];
            //int userid = user.ID;
            //PagedList<U_Member> mList = _mservice.QueryMemberListByUser(search,user.ID, view);
            PagedList<U_Member> mList = _mservice.QueryDeptAssignMemberList(search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<U_Member>(mList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        [HttpPost]
        public JsonResult AssignDept(MemberSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            //S_User user =(S_User)System.Web.HttpContext.Current.Session["LoginUseInfo"];
            //int userid = user.ID;
            //PagedList<U_Member> mList = _mservice.QueryMemberListByUser(search,user.ID, view);
            PagedList<U_Member> mList = _mservice.QueryAssignDeptMemberList(search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<U_Member>(mList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }


        public JsonResult SendEmail(string name)
        {
            JsonSMsg rMsg = new JsonSMsg();
            ViewBag.Name = name;
            //放入会话中
            Session["membername"] = name;
            //设置session有效时间 1分钟
            Session.Timeout = 600;
            CreateTimeoutMessage("localhost", name);
            //112.65.163.22
            return Json(rMsg);
        }

        public static string CreateTimeoutMessage(string server, string name)
        {
            string Success = "发送成功";
            try
            {
                //string _to = "296621205@qq.com";
                //string _from = "abc12671296@163.com";
                //string _subject = "Hello World!";
                //string _body = "打开链接 http://localhost:14008/Member/Reply.html?MemeberName=" + name + " 激活账号";
                //MailMessage message = new MailMessage();
                //message.From = new MailAddress(_from);
                ////可以利用MailMessage.To.Add方法增加要发送的邮件地址
                //message.To.Add(new MailAddress("3058373919@qq.com"));
                //message.To.Add(new MailAddress(_to));
                //message.Subject = _subject;
                //message.Body = _body;
                ////添加附件
                ////Attachment a = new Attachment(@"C:/Users/Administrator/Desktop/smtpclient.rar"); 
                ////message.Attachments.Add(a); 
                ////设置邮箱的地址或IP
                //SmtpClient client = new SmtpClient(server);
                ////设置邮箱端口
                //client.Host = "smtp.163.com";
                ////pop3端口:110, 
                ////smtp端口是:25 
                //client.Port = 25;
                ////设置超时时间
                //client.Timeout = 9999;
                ////要输入邮箱用户名与密码 
                //client.Credentials = new NetworkCredential("abc12671296@163.com", "");
                //client.Send(message);
            }
            catch (Exception ex)
            {
                Success = ex.ToString();
            }
            return Success;
        }

        //****编辑 新增 会员信息*******//
        public ActionResult MemberEdit(int? id)
        {
         
            Member_EX member = null;
            if (id.HasValue)
            {
                member = _mservice.GetMember(id.Value);
            }
            else
            {
                member = new Member_EX();
                //新增的时候先查询前面人的编号，没有就是0001
                string date = DateTime.Now.ToString("yyyyMMdd");
                Member_EX lastMember = _mservice.SelectLastMemberToday(date);
                if (lastMember == null)
                {
                    member.MemberID = "QJJC" + date + "0001";
                }
                else
                {
                    int number = Convert.ToInt32(lastMember.MemberID.Substring(12)) + 1;
                    member.MemberID = "QJJC" + date + number.ToString("0000");
                }
                //给默认值
                member.Sex = 1;//默认男
                member.Name = "无";
                member.Nationality = "中国大陆";
                member.IDType = 1;
                member.EmergencyContactIDType = 1;
                member.ReceiveFileType = 2;
                member.Mobilenumber = "";
                member.EmergencyContactMobileNumber = "";
                member.ManagerID = "";
                member.RecommendCode = "";
            }
            
            if (member.SFTUserName != "")
            {
                ViewBag.UserAccount = LY.ShengPayApi.Services.Get.GetUserAccount(_apiAddress, _merchantNo, member.SFTUserName);
            }

         
            return View(member);
        }
        //编辑新增 待分配到部门
        public ActionResult DeptAssignEdit(int? id)
        {

            Member_EX member = null;
            if (id.HasValue)
            {
                member = _mservice.GetMember(id.Value);
            }
            else
            {
                member = new Member_EX();
            }
            return View(member);
        }
        public ActionResult MyMemberEdit(int? id)
        {
            Member_EX member = null;
            if (id.HasValue)
            {
                member = _mservice.GetMember(id.Value);
            }
            else
            {
                member = new Member_EX();
            }
            return View(member);
        }
        public ActionResult DeptMemberEdit(int? id)
        {

            Member_EX member = null;
            if (id.HasValue)
            {
                member = _mservice.GetMember(id.Value);
            }
            else
            {
                member = new Member_EX();
            }
            return View(member);
        }
        //****保存会员信息*******//
        [HttpPost]
        public JsonResult MemberSave(int? id, U_Member member, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                string errmsg = "";
                if (!Validate(member, out errmsg))
                {
                    rMsg.Status = -1;
                    rMsg.Message = errmsg;
                    return Json(rMsg);
                }

                member.RemoveUpdateColumn("Password");
                if (member.ManagerID == null)//因为不能为null 所以给初始值
                {
                    member.ManagerID = "";
                }
                if (member.RecommendCode == null)//因为不能为null 所以给初始值
                {
                    member.RecommendCode = "";
                }
                int ret = _mservice.SaveMember(member);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Data = ret;
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        //分配到部门
        [HttpPost]
        public JsonResult AssignDepts(string mids, string did, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {

                if (!string.IsNullOrEmpty(mids) && !string.IsNullOrEmpty(did))
                {
                    int ret = _mservice.AssignDept(mids, did);
                    if (ret > 0)
                    {
                        rMsg.Status = 1;
                        rMsg.Data = ret;
                    }
                    else
                    {
                        rMsg.Status = -1;
                        rMsg.Message = "意外错误，请稍后重试！";
                    }
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "参数有误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        //分配到员工
        [HttpPost]
        public JsonResult AssignUser(string mids, string uid, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {

                if (!string.IsNullOrEmpty(mids) && !string.IsNullOrEmpty(uid))
                {
                    int ret = _mservice.AssignUser(mids, uid);
                    if (ret > 0)
                    {
                        rMsg.Status = 1;
                        rMsg.Data = ret;
                    }
                    else
                    {
                        rMsg.Status = -1;
                        rMsg.Message = "意外错误，请稍后重试！";
                    }
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "参数有误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }

        //****编辑  会员密码*******//
        [HttpPost]
        public JsonResult PwdSave(int? id, U_Member member, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                //if (!Validate(member, out errmsg))
                //{
                //    rMsg.Status = -1;
                //    rMsg.Message = errmsg;
                //    return Json(rMsg);
                //}
                int ret = _mservice.SaveMember(member);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Data = ret;
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }
        private static bool Validate(U_Member member, out string errmsg)
        {
            errmsg = "";
            if (member == null)
            {
                errmsg = "参数错误！";
                return false;
            }
            //if (member.ID <= 0)
            //{
            //    errmsg = "请选择会员！";
            //    return false;
            //}
            //if (!ValidateUtil.IsValidUserName(member.Name))
            //{
            //    errmsg = "用户名的长度（4-20个字符）及内容（只能是汉字、字母、下划线、数字）合法！";
            //    return false;
            
            //}
            //if (!ValidateUtil.IsValidZip(member.PostCode))
            //{
            //    errmsg = "邮编格式错误！";
            //    return false;
            
            //}
            //if (!ValidateUtil.IsValidPassword(member.Password))
            //{
            //    errmsg = "密码长度（6-16字符）";
            //    return false;
            //}
            //if (!ValidateUtil.IsEmail(member.Email))
            //{
            //    errmsg = "电子邮件格式不正确!必须包含‘@’符号";
            //    return false;

            //}
            //if (!ValidateUtil.IsValidPhone(member.Tel))
            //{
            //    errmsg = "固定电话格式不正确! 例如：021-0000000";
            //    return false;

            //}
            if (!ValidateUtil.IsValidMobile(member.Mobilenumber))
            {
                errmsg = "手机号码格式不正确!";
                return false;

            }
            return true;
        }
        private static bool Validpwd(U_Member member,out string errmsg) {
            errmsg = "";
            if (member == null)
            {
                errmsg = "参数错误！";
                return false;
            }
            //if (member.ID <= 0)
            //{
            //    errmsg = "请选择会员！";
            //    return false;
            //}
            if (!ValidateUtil.IsValidPassword(member.Password))
            {
                errmsg = "密码的长度（6-16个字符）及内容（只能是字母、下划线、数字）合法！";
                return false;
            }
            return true;
        
        }
        //*****删除***//
        [HttpPost]
        public ActionResult MemberDelete(int id, FormCollection collection)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                if (id <= 0)
                {
                    rMsg.Status = -1;
                    rMsg.Message = "参数错误！";
                    return Json(rMsg);
                }

                int ret = _mservice.DeleteMember(id);
                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Data = ret;
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {
                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }


        /// <summary>
        /// 给所有成员发送系统消息
        /// </summary>
        /// <param name="information"></param>
        /// <param name="collection"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SendInformation(U_Information information, FormCollection collection)
        {
            JsonSMsg rmsg = new JsonSMsg();
            int result = 0;
            try
            {
                if (information == null)
                {
                    rmsg.Status = -1;
                    rmsg.Message = "参数错误！";
                    return Json(rmsg);
                }
                else
                {
                    //information.CreateDate = DateTime.Now;//当前时间
                    //information.FromUser = 0;//接受消息用户的编号
                    //information.ToUser = 0;
                    //information.Status = 1;
                    //int result = _Iservice.AddInformation(information);
                    List<U_Member> listid = _mservice.GetID();
                    if (listid.Count <= 0)
                    {
                        rmsg.Status = -1;
                        rmsg.Message = "抱歉！暂时无用户。";
                        return Json(rmsg);
                    }
                    else
                    {
                        //Id, Title, Content, CreateDate, FromUser, ToUser, Status
                        foreach (var item in listid)
                        {
                            information.Title = collection["Title"];
                            information.Content = collection["Content"];
                            information.CreateDate = DateTime.Now;
                            information.FromUser = 0;
                            information.ToUser = item.ID;
                            information.Status = 1;
                            result = _Iservice.AddInformation(information);
                        }
                        if (result>0)
                        {
                          rmsg.Status = 1;
                        rmsg.Data = result;
                        return Json(rmsg);   
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                rmsg.Status = -1;
                rmsg.Message = ex.Message;
                return Json(rmsg);
                throw;
            }
            return Json(rmsg);
        }

       

        /**
         * 
         * 邮箱验证result
         * */
        public ActionResult Reply()
        {
            string membername = Request.QueryString["MemeberName"];
            
            //int ret = _mservice.ValidateUserNo(membername);
            return View();
        }

        //跟进
        public ActionResult Followup()
        {
            return View();
        }

        //添加跟进信息
        public ActionResult AddFollowUp()
        {
            return View();
        }

      

        //会员统计管理
        public ActionResult MemberStatistics()
        {
            return View();
        }

        //会员统计列表分页查询
        [HttpPost]
        public ActionResult MemberStatisticslist(MemberStatisticsSearch search, FormCollection form)
        {
            PageView view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];
            S_User user = (S_User)System.Web.HttpContext.Current.Session["LoginUseInfo"];
            int userid = user.ID;
            PagedList<U_MemberStatistics_EX> mList = _mservice.QueryMemberStatisticsList(search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<U_MemberStatistics_EX>(mList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        //检查身份证，邮箱，手机号码是否重复
        public ActionResult ValidateAll(string idCode, string Mobilenumber, string Email, int id)
        {
            string result = _mservice.ValidateAll(idCode, Mobilenumber, Email, id);
            return Content(result);
        }


        #region 会员登陆日志

        public ActionResult MemberLog()
        { 
            return View();
        }
        [HttpPost]
        public ActionResult MemberLog( MemberLoginSearch search, FormCollection form)
        {
            var view = new PageView(form);
            string colkey = form["colkey"];
            string colsinfo = form["colsinfo"];

            search.MemberName = form["MemberName"];

            var user =(S_User)System.Web.HttpContext.Current.Session["LoginUseInfo"];
            int userid = user.ID;
            PagedList<U_MemberLoginLog> mList = _memberLogService.QueryMemberLoginList(search, view);
            JsonQTable fdata = JsonQTable.ConvertFromPagedList<U_MemberLoginLog>(mList, colkey, colsinfo.Split(','));
            return Json(fdata);
        }

        #endregion

        //移除黑名单用户
        [HttpPost]
        public JsonResult deleteBlackMember(int id)
        {
            JsonSMsg rMsg = new JsonSMsg();
            try
            {
                if (id <= 0)
                {
                    rMsg.Status = -1;
                    rMsg.Message = "参数错误！";
                }
                U_Member member = _mservice.getMemberInfo(id);
                member.Status = 1;
                int ret = _blackservice.updateMemberStutas(member);
                //U_BlackMember blackMember = _blackservice.getBlackMember(id);

                  ret = _blackservice.DeleteBlackMember(member.ID);
                //U_BlackMember member = _blackservice.getBlackMember(id);
                //ret = _memberservice.updateMemberStatus(member.MemberID, 1);

                if (ret > 0)
                {
                    rMsg.Status = 1;
                    rMsg.Message = "操作成功！";
                }
                else
                {
                    rMsg.Status = -1;
                    rMsg.Message = "意外错误，请稍后重试！";
                }
            }
            catch (Exception ex)
            {

                rMsg.Status = -1;
                rMsg.Message = ex.Message;
            }
            return Json(rMsg);
        }
    }
}
